/**
 * 
 */
package com.massyframework.beanskin.launcher.scanning.maven;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.massyframework.beanskin.util.IOUtils;
import com.massyframework.beanskin.util.exceptioncollect.ExceptionCollectUtils;

/**
 * {@link DefaultMavenProjectRepository},缺省的Maven项目仓储
 * @author huangkh
 *
 */
public final class DefaultMavenProjectRepository extends AbstractMavenProjectRepository {
	
	private Map<String, String> pathMap;
	/**
	 * 
	 */
	public DefaultMavenProjectRepository() {
		this.pathMap = new HashMap<>();
	}
	
	
	
	@Override
	public void init() {
		File pomFile = this.getPomXmlFile();
		if (pomFile != null) {
			DevelopingMavenProjectResolver resolver =
					new DefaultDevelopingMavenProjectResolver(this);			
			this.loadModulePaths(pomFile, resolver);
			this.doInit(resolver);
		}
	}
	
	

	@Override
	protected MavenProject findDeploveingMavenProject(Coordinate coordinate) {
		String key = this.getKey(coordinate);
		String path = this.pathMap.get(key);
		if (path != null) {
			File pomFile = new File(path, "pom.xml");
			if (pomFile.exists()) {
				try {
					DevelopingMavenProjectResolver resolver =
							new DefaultDevelopingMavenProjectResolver(this);		
					return resolver.parse(pomFile);
				}catch(Exception e) {
					if (logger.isErrorEnabled()) {
						logger.error("resolver maven project failed: " + pomFile.getAbsolutePath() + ".", e);
					}
					ExceptionCollectUtils.addException(e);
				}
			}
		}
		return null;
	}

	protected String getKey(Coordinate coordinate) {
		return coordinate.getGroupId().concat("_").concat(coordinate.getArtifactId()).concat("_").concat(coordinate.getVersion());
	}


	/**
	 * 加载模块路经
	 * @param pomFile
	 * @param resolver
	 */
	protected void loadModulePaths(File pomFile, DevelopingMavenProjectResolver resolver){
		try {
			DevelopingMavenProject project = resolver.parse(pomFile);
			if (project != null) {
				project = this.recursiveRootProject(project, resolver);
				
				File targetDir = new File(project.getBaseDir(), "target");
				File modulesDir = new File(targetDir, ".modules");
				if (modulesDir.exists()) {
					File[] files = modulesDir.listFiles();
					if (files != null) {
						for (File file: files) {
							this.parserFile(file);
						}
					}
				}
			}
		}catch(Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("resolver maven project failed: " + pomFile.getAbsolutePath() + ".", e);
			}
			ExceptionCollectUtils.addException(e);
		}
	}
	
	/**
	 * 解析路经文件
	 * @param pathFile
	 */
	protected void parserFile(File pathFile) {
		String name = pathFile.getName();
		FileInputStream inputStream = null;
		BufferedReader reader = null;
		try {
			inputStream =	new FileInputStream(pathFile);
			reader = new BufferedReader(new InputStreamReader(inputStream));
			
			String line = null;
			while((line = reader.readLine()) != null)
			{
				if (line.startsWith("#")) {
					continue;
				}
				
				this.pathMap.put(name, line);
				break;
			}
		}catch(Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("read file failed: " + pathFile + ".", e);
			}
			ExceptionCollectUtils.addException(e);
		}finally {
			IOUtils.close(reader);
			IOUtils.close(inputStream);
		}
	}

	/**
	 * 递归遍历到根项目
	 * @param project {@link DevelopingMavenProject},开发中的maven项目
	 * @return {@link DevelopingMavenProject},根项目
	 * @throws Exception 
	 */
	protected DevelopingMavenProject recursiveRootProject(DevelopingMavenProject project,
			DevelopingMavenProjectResolver resolver) throws Exception {
		//加载父工程
		ParentCoordinate parent = project.getParentCoordinate();
		if (parent != null) {
			File parentPomFile = this.locateParentPomXml(parent, project.getBaseDir());
			if (parentPomFile != null) {
				DevelopingMavenProject parentProject = resolver.parse(parentPomFile);
				if (parentProject != null) {
					return this.recursiveRootProject(parentProject, resolver);
				}
			}
		}
		
		return project;
	}

	/**
	 * 获取PomFile
	 * @return {@link File}
	 */
	protected File getPomXmlFile() {
		File targetDir = this.getTargetDir();
		if (targetDir != null) {
			File pomFile = new File(targetDir.getParentFile(), "pom.xml");
			if (pomFile.exists()) {
				return pomFile;
			}
		}
		
		return null;
	}
	
	/**
	 * 获取Taget目录
	 * @return {@link File}
	 */
	private File getTargetDir() {
		URL url = this.getClass().getClassLoader().getResource("/");
		if (url == null) {
			url = this.getClass().getClassLoader().getResource("");
		}
		String path = url.getPath();	
		File file = new File(path);
		File parent = file.getParentFile();
		if (parent.getName().equals("target")) {
			return parent;
		}
		
		return null;
	}
}
